import Collection from 'ol/Collection'

/* DOM元素的覆盖物Overlayex图层，用于在地图上显示DOM覆盖物
  opt = {
    id,//图层ID
    map, //ol.map实例
    overlayexs，//array<Overlayex>
  }
*/
class TyOverlayexLayer {
  constructor(opt) {
    this.internalOverlayexs = new Collection()
    this.overlayexIdIndex = {}
    this.layerId = opt.id || undefined
    this.map = opt.map
    this.overlayexs = opt.overlayexs || undefined
    this.internalOverlayexs.on('add', (event) => {
      const overlayex = event.element
      if (overlayex.getId()) {
        this.overlayexIdIndex[overlayex.getId()] = overlayex
      }
    }, this)
    this.internalOverlayexs.on('remove', (event) => {
      const id = event.element.getId()
      if (id !== undefined) {
        delete this.overlayexIdIndex[id.toString()]
      }
    }, this)
    if (this.overlayexs && this.overlayexs.length > 0) {
      for (let i = 0; i < this.overlayexs.length; i++) {
        this.addOverlayex(this.overlayexs[i])
      }
    }
  }

  addOverlayex(overlayex) {
    this.internalOverlayexs.push(overlayex)
    this.map.addOverlay(overlayex.createOverlay())
  }

  removeOverlayex(overlayex) {
    this.internalOverlayexs.remove(overlayex)
    this.map.removeOverlay(overlayex.getOverlay())
  }

  clear() {
    const overlayexs = this.internalOverlayexs.getArray()
    for (let i = overlayexs.length - 1; i >= 0; i--) {
      this.removeOverlayex(overlayexs[i])
    }
  }

  getOverlayexById(id) {
    return this.overlayexIdIndex[id]
  }

  getOverlayexs() {
    return this.internalOverlayexs
  }

  getId() {
    return this.layerId
  }

  getCount() {
    return this.internalOverlayexs.getLength()
  }
}

export default TyOverlayexLayer
